package chapter15;

import chapter11.Role;
import chapter13.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @create 2018-04-19 下午4:26
 */
@Controller
@RequestMapping("/attribute")
@SessionAttributes(names = {"id"}, types = {Role.class})
public class AttributeController {
    @Autowired
    private UserService userService;

    @RequestMapping("/index")
    public ModelAndView index() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("reqattribute");
        return mv;
    }

    @RequestMapping("/index2")
    public ModelAndView index2() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("sessionAttribute2");
        return mv;
    }

    @RequestMapping("/requestAttribute")
    public ModelAndView reqAttr(@RequestAttribute("id") Long id) {
        ModelAndView mv = new ModelAndView();
        Role role = userService.getRole(id);
        mv.addObject(role);
        mv.setView(new MappingJackson2JsonView());
        return mv;
    }

    @RequestMapping("/sessionAttributes")
    public ModelAndView sessionAttrs(@RequestParam("id") Long id) {
        ModelAndView mv = new ModelAndView();
        Role role = userService.getRole(id);
        mv.addObject("role", role);
        mv.addObject("id", id);
        mv.setViewName("sessionAttribute");
        return mv;
    }

    @RequestMapping("/sessionAttribute")
    public ModelAndView sessionAttr(@SessionAttribute("id") Long id) {
        ModelAndView mv = new ModelAndView();
        Role role = userService.getRole(id);
        mv.addObject("role", role);
        mv.setView(new MappingJackson2JsonView());
        return mv;
    }
}
